from influxdb_client import InfluxDBClient, Point
from influxdb_client.client.write_api import SYNCHRONOUS
import time
from .setting import *
# 导入setting作为st


class InfluxdbIO:
    def __init__(self, url=None, token=None, org=None, time_step: int = None):
        if not url:
            url = default_url
        if not token:
            token = default_token
        if not org:
            org = default_org
        if not time_step:
            time_step = int(default_time_step)

        self.org = org
        try:
            self.client = InfluxDBClient(url=url, token=token, org=org)
            self.write_api = self.client.write_api(write_options=SYNCHRONOUS)
            self.query_api = self.client.query_api()
        except Exception as e:
            print(f'连接失败 : {e}')
        self.time_step = time_step

    def write(self, db_name: str, table_name: str, data: dict, tag: dict, time_ns: int = None):
        if data is None or not isinstance(data, dict) or len(data) == 0:
            return
        if time_ns is None:
            time_ns = int(time.time() * 1e9)
        time_ns = int(round(time_ns / self.time_step) * int(self.time_step))

        point = Point(table_name)
        for k in data:
            point.field(k, data[k])
        for k in tag:
            point.tag(k, tag[k])
        point.time(time_ns)
        self.write_api.write(bucket=db_name, record=point)

    def read(self, query: str):
        return self.query_api.query(org=self.org, query=query)

    def close(self):
        self.client.close()


if __name__ == '__main__':
    data = '1724737490 15 20 36'
    head = ['t', 'ax', 'ay', 'az']
    d = {k: float(v) for (k, v) in zip(head, data.split(' '))}
    # inio = InfluxdbIO(st.default_url, st.default_token, st.default_org)
    # 获取d中的t作为时间戳
    # inio.write('test_influxdb', 'test', d, {})